package com.yb.proxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.yb.proxy.MonitorSession;

/**
 * jdk动态代理要求代理的类必须实现一个Interface
 * @author yanbiao
 *
 */
public class DynamicProxy implements InvocationHandler {
	
	private Object target;
	public DynamicProxy(Object target){
		this.target = target;
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		//代理对象执行invoke方法前后执行begin，end方法
		MonitorSession.begin(method.getName());
		Object object = method.invoke(target, args);
		MonitorSession.end();
		return object;
	}
	
	/**
	 * 获取代理对象的方法
	 */
	@SuppressWarnings("unchecked")
	public <T>T getProxy(){
		return (T)Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
	}
}
